package com.qf.dao;

import com.qf.pojo.Student;
import com.qf.util.DBUtils;
import com.qf.util.DateUtil;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 千锋健哥
 */
public class StudentDaoImpl implements StudentDao{

    @Override
    public void insertStudent(Student student) {
        try {
            Connection connection = DBUtils.getConnection();
            Statement statement = connection.createStatement();

            String sql = "insert into student (name, age, birthday, sex, clazz) " +
                    " values('"+ student.getName() +"', "+ student.getAge()+", '"
                    + DateUtil.dateToStr(student.getBirthday())+"', "+student.getSex()+", "
                    + student.getClazz()+")";

            statement.executeUpdate(sql);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 作业
     * @param student
     */
    @Override
    public void updateStudent(Student student) {
        try {
            Connection connection = DBUtils.getConnection();
            Statement statement = connection.createStatement();
            statement.executeUpdate("");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 作业
     * @param id
     */
    @Override
    public void deleteStudent(Integer id) {
        try {
            Connection connection = DBUtils.getConnection();
            Statement statement = connection.createStatement();
            statement.executeUpdate("");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Student> findAll() {
        try {
            Connection connection = DBUtils.getConnection();
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery("select * from student");

            List<Student>  studentList = new ArrayList<>();
            //判断resultSet不为空
            if (resultSet != null) {
                //遍历resultSet取数据
                while (resultSet.next()) {
                    //创建学生丢向
                    Student student = new Student();
                    student.setId(resultSet.getInt("id"));
                    student.setName(resultSet.getString("name"));
                    student.setAge(resultSet.getInt("age"));
                    student.setSex(resultSet.getInt("sex"));
                    student.setBirthday(resultSet.getDate("birthday"));
                    student.setClazz(resultSet.getInt("clazz"));
                    //student对象放入集合中
                    studentList.add(student);
                }
            }
            return studentList;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

}
